/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */
package com.hopes.bizz.risk.setting.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hopes.bizz.common.core.util.StringUtils;
import com.hopes.bizz.risk.hid.listener.ImageModifyHandler;
import com.hopes.bizz.risk.setting.entity.RiskSafetyWarningLabelEntity;
import com.hopes.bizz.risk.setting.mapper.RiskSafetyWarningLabelMapper;
import com.hopes.bizz.risk.setting.service.RiskSafetyWarningLabelService;
import com.hopes.bizz.risk.setting.vo.RiskSafetyWarningLabelExcelVO;
import com.hopes.boss.admin.api.feign.RemoteFileService;
import com.hopes.boss.common.core.constant.SecurityConstants;
import com.hopes.boss.common.data.tenant.TenantContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import java.util.*;

/**
 * 安全警示标示
 *
 * @author liujiaqi
 * @date 2023-07-24 10:30:35
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RiskSafetyWarningLabelServiceImpl extends ServiceImpl<RiskSafetyWarningLabelMapper, RiskSafetyWarningLabelEntity> implements RiskSafetyWarningLabelService {

    private final RemoteFileService remoteFileService;

    @Override
    public void export(RiskSafetyWarningLabelEntity riskSafetyWarningLabel, ServletOutputStream outputStream) {
        final List<RiskSafetyWarningLabelExcelVO> excelVOList = new ArrayList<>();
        final List<RiskSafetyWarningLabelEntity> list = list(Wrappers.query(riskSafetyWarningLabel));
        for (int i = 0; i < list.size(); i++) {
            final RiskSafetyWarningLabelEntity entity = list.get(i);
            final RiskSafetyWarningLabelExcelVO excelVO = new RiskSafetyWarningLabelExcelVO();

            excelVO.setIndex(i + 1);
            excelVO.setType(entity.getTypeStr());
            excelVO.setLabelName(entity.getLabelName());
            Optional.ofNullable(entity.getImage()).ifPresent(url -> {
                try {
                    excelVO.setImage(buildImage(url));
                }catch (Exception e) {
                    log.error("安全警示标记导出，{}转URL异常 ！", url, e);
                }
            });
            excelVOList.add(excelVO);
        }
        ImageModifyHandler imageModifyHandler = buildImagesByte(4, excelVOList);
        // 写入数据
        EasyExcel.write(outputStream, RiskSafetyWarningLabelExcelVO.class).registerWriteHandler(imageModifyHandler).sheet().doWrite(excelVOList);
    }

    private byte[] buildImage(String url) {
        if (StringUtils.isEmpty(url)) {
            return new byte[0];
        }
        String imgName = url.split(StringUtils.SLASH)[url.split(StringUtils.SLASH).length - 1];
        String tenantBucketName = TenantContextHolder.getTenantBucketName();
        return remoteFileService.getFileStream(tenantBucketName, imgName, SecurityConstants.FROM_IN);
    }

    private ImageModifyHandler buildImagesByte(int column, List<RiskSafetyWarningLabelExcelVO> exportList) {
        final HashMap<String, List<byte[]>> images = new HashMap<>();
        final HashMap<Integer, Integer> columnImageMostCount = new HashMap(){
            private static final long serialVersionUID = 1468378912795571599L;
            {
                put(column, 1);
            }
        };
        for (int i = 0; i < exportList.size(); i++) {
            images.put(i + 1 + "," + column, Collections.singletonList(exportList.get(i).getImage()));
        }
        return new ImageModifyHandler(images, columnImageMostCount);
    }


}
